package com.yds.ydsdatasetbackend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yds.ydsdatasetbackend.common.Category;
import com.yds.ydsdatasetbackend.model.entity.PatientGroup;
import com.yds.ydsdatasetbackend.service.PatientGroupService;
import com.yds.ydsdatasetbackend.mapper.PatientGroupMapper;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
* @author YDS
* @description 针对表【patient_group(病人分组表)】的数据库操作Service实现
* @createDate 2025-04-09 13:59:59
*/
@Service
public class PatientGroupServiceImpl extends ServiceImpl<PatientGroupMapper, PatientGroup>
    implements PatientGroupService{


    @Override
    public List<Category> getTree(Long id) {
        QueryWrapper<PatientGroup> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId", id);
        List<PatientGroup> patientGroups = this.baseMapper.selectList(queryWrapper);
        HashMap<Long, Category> categoryHashMap = new HashMap<>();
        // 开始构建树形结构
        for (PatientGroup patientGroup : patientGroups) {
            Category category = new Category(patientGroup.getId(), patientGroup.getParentId(), patientGroup.getGroupName());
            categoryHashMap.put(patientGroup.getId(), category);
        }
        List<Category> categories = new ArrayList<>();
        for (PatientGroup patientGroup : patientGroups) {
            if(patientGroup.getParentId() == -1) {
                Category node = categoryHashMap.get(patientGroup.getId());
                if(node == null) continue;
                categories.add(node);
            }else {
                Category parent = categoryHashMap.get(patientGroup.getParentId());
                Category node = categoryHashMap.get(patientGroup.getId());
                if(parent == null || node == null) continue;
                parent.addChild(node);
            }
        }
        return categories;
    }
}




